package com.example.service;

import cn.hutool.core.util.ObjectUtil;
import com.example.common.Constants;
import com.example.common.enums.ResultCodeEnum;
import com.example.common.enums.RoleEnum;
import com.example.entity.User;
import com.example.exception.CustomException;
import com.example.mapper.UserMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import net.sf.jsqlparser.util.validation.metadata.NamedObject;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;

import static net.sf.jsqlparser.util.validation.metadata.NamedObject.user;


@Service
public class UserService {
    //mapper
    @Resource
    private UserMapper userMapper;

    public void add(User user) {
        //1.判断账号是否重复
       User dbuser= userMapper.selectByUsername(user.getUsername());
        if(dbuser!=null){
            //账号重复
            throw new CustomException(ResultCodeEnum.USER_EXIST_ERROR);
        }
        //2.判断密码是否为空
        if (ObjectUtil.isEmpty(user.getPassword())){
            //密码为空,设置默认密码为123
            user.setPassword(Constants.USER_DEFAULT_PASSWORD);
        }
        //3.判断昵称是否为空
        if(ObjectUtil.isEmpty(user.getName()))
        {
            //昵称为空,设置默认昵称为账号
            user.setName(user.getUsername());
        }
        //4.默认用户角色
        user.setRole(RoleEnum.USER.name());
            userMapper.insert(user);
    }


    public void deleteById(Integer id) {
        userMapper.deleteById(id);
    }

    public void deleteBatch(List<Integer> ids) {
        userMapper.deleteBatch(ids);
    }

    public User selectById(Integer id) {
        return userMapper.selectById(id);
    }

    public List<User> selectAll(User user) {
        return userMapper.selectAll(user);
    }

    public PageInfo<User> selectPage(User user, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        List<User> list=userMapper.selectPage(user);
        return PageInfo.of(list);
    }

    public void update(User user) {
        userMapper.update(user);
    }
}
